document.write("<script type='text/javascript' src='/js/abi.js'></script>");

var web3;
var gasPrice;


App = {
    web3Provider: null,
    contracts: {},
    init: function () {
        return App.initWeb3();
    },

    initWeb3: function () {


        // Initialize web3 and set the provider to the testRPC.
        if (typeof web3 !== 'undefined') {
            App.web3Provider = web3.currentProvider;
            web3 = new Web3(web3.currentProvider);
        } else {
            App.web3Provider = new Web3.providers.HttpProvider('https://mainnet.infura.io/c8LMJFLLL7rUEBtxozvJ');
            web3 = new Web3(App.web3Provider);
        }
        return App.initContract();
    }
    ,

    initContract: function () {

        // 通过ABI和地址获取已部署的合约对象
        App.contracts.RecreationChain = new web3.eth.Contract(abi, address);
        App.contracts.RecreationChain.setProvider(App.web3Provider);
        // App.create();
        // App.getBalances();
    }
    ,


    getBalances: function () {
        console.log('Getting balances...');

        web3.eth.getAccounts(function (error, accounts) {
            if (error) {
                console.log(error);
            }
            var account = accounts[0];

            App.contracts.RecreationChain.methods.balanceOf(account).call(function (err, result) {
                var balance = web3.utils.fromWei(result, 'ether');

                if (!err) {
                    $('#TTBalance').text(balance);
                } else {
                    console.log(err);
                }
            });

        });
    }
    ,
    //to 钱包，精度是8位
    transferTccoin: function (id, formAddress, toAddress, num, privateKey) {

        var nonce;
        console.log('transfer start...');

        // 获取gasPrice 大概是0.000000041ETH
        web3.eth.getGasPrice().then(function (result) {
            gasPrice = result;
            console.log("gasPrice==========" + gasPrice);

        });

        web3.eth.getTransactionCount(toAddress, "pending").then(function (value) {
            console.log("value=============" + value);
            nonce = parseInt(value) + 1;
        })

        // //转账需要私钥
        var b = num * 100000000;


        web3.eth.accounts.signTransaction(
            {
                nonce: nonce,
                to: address,
                form: formAddress,
                data: App.contracts.RecreationChain.methods.transfer(toAddress, b).encodeABI(),
                gasPrice: gasPrice,
                gas: 55000
            }, "0x" + privateKey).then(function (res) {
            console.log(res.rawTransaction);
            web3.eth.sendSignedTransaction(res.rawTransaction).then(function (res) {
                console.log(res.transactionHash);
                updateTransferAccounts(id, res.transactionHash);
            });
        });


    },


    encrypt: function () {
        console.log('encrypt...');
        //'c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3', '12345678'
        console.log(web3.version);
        var str = web3.eth.accounts.encrypt("304649b6f99ab6c43bfc1b88eadfd97663814e1d0c7bc2bf2b32810b1dd33b99", "123456");
        //转json字符串
        var homeObj = JSON.stringify(str);
        console.log(homeObj)
        // $('#str').text(homeObj);


    }
}
;

$(function () {
    $(window).load(function () {
        App.init();
    });
});

/**
 * 转账
 */
// function batchTransferTccoin() {
//     var count = 0;
//     var size = 0;
//     $.ajax({
//         type: "POST",
//         async: false,
//         url: "/transferAccountsExcel/queryList",
//         success: function (msg) {
//             var data = eval(msg);
//             size = data.length;
//             if (size > 0) {
//                 for (var i = 0; i < size; i++) {
//                     var formAddress = data[i].fromAccountNo;
//                     var toAddress = data[i].toAccountNo;
//                     var num = data[i].transferNum;
//                     var id = data[i].id;
//                     var privateKey = data[i].privateKey;
//                     var flag = web3.utils.isAddress(toAddress);
//                     if (flag) {
//                         if (null != formAddress && null != toAddress && null != num && null != id && 0 != num && null != privateKey) {
//                             App.transferTccoin(id, formAddress, toAddress, num, privateKey);
//                         } else {
//                             alert("导入的数据不完整！");
//                         }
//                     } else {
//                         alert("钱包地址不正确！");
//                     }
//                     count++;
//                     sleep(10000);
//                 }
//             }
//         }
//     });
//     if (count == size) {
//         alert("批量转账完成!");
//     }
// }

batchTransfer
function batchTransferTccoin() {
    $('#loading').show()
    $("#transfer").attr('disabled', 'disabled')
    setTimeout(function () {
        $.ajax({
            type: "POST",
            async: false,
            url: "/tblTransferAccount/batchTransfer",
            success: function (msg) {
                $("#transfer").removeAttr('disabled')
                alert(msg);
                $('#loading').hide()
                window.location.reload();
            }
        });
    }, 30)


}

/**
 * 更新hash值
 */
function updateTransferAccounts(id, hash) {

    $.ajax({
        type: "POST",
        async: false,
        data: "id=" + id + "&hash=" + hash,
        url: "/transferAccountsExcel/updateTransferAccounts",
        success: function (msg) {
            if (2 == msg) {
                alert("更新hash值失败！");
            }
        }
    });

}


function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}


function excel() {
    window.location.href = "/transferAccountsExcel/excelToPage";
}

